package com.haoqi.document.template.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.haoqi.document.template.dto.in.ExcelExportWithUrlReqDtoIn;
import com.haoqi.document.template.service.ExcelExportService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class ExcelExportServiceImpl implements ExcelExportService {

    @Value("${endpoints.prefix}")
    private String prefix;

    @Value("${endpoints.path}")
    private String path;

    @Override
    public String excelDataExport(ExcelExportWithUrlReqDtoIn dtoIn) throws Exception {
        URL url = new URL(dtoIn.getFileUrl());
        HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setUseCaches(false);

        JSONArray jsonArray = JSONArray.parseArray(dtoIn.getData());
        Context context = new Context();
        context.putVar("data", jsonArray);

        //加载模板，从文件url获取
        //InputStream exIs = new FileInputStream(new File("F:\\gov-ch.xlsx"));
        InputStream exIs = httpUrlConnection.getInputStream();

        File tempFile = new File(path + File.separator + System.currentTimeMillis() + "_data.xls");
        OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));
        JxlsHelper.getInstance().processTemplate(exIs, os, context);

        String fileUrl = prefix + tempFile.getPath();
        return fileUrl;
    }
}